/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { Encoding } from './Encoding';
import { WordArray } from './lib-WordArray';

export class Utf16BE implements Encoding {
  /**
   * Converts a word array to a UTF-16 BE string.
   *
   * @param wordArray The word array.
   *
   * @return The UTF-16 BE string.
   *
   * @example
   *
   *     let utf16String = Utf16.stringify(wordArray);
   */
  public stringify(wordArray: WordArray): string {
    // Shortcuts
    var words = wordArray.words;
    var sigBytes = wordArray.sigBytes;

    // Convert
    var utf16Chars = [];
    for (var i = 0; i < sigBytes; i += 2) {
      var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff;
      utf16Chars.push(String.fromCharCode(codePoint));
    }
    return utf16Chars.join('');
  }

  /**
   * Converts a UTF-16 BE string to a word array.
   *
   * @param utf16Str The UTF-16 BE string.
   *
   * @return The word array.
   *
   * @example
   *
   *     let wordArray = Utf16.parse(utf16String);
   */
  public parse(utf16Str: string): WordArray {
    // Shortcut
    var utf16StrLength = utf16Str.length;
    // Convert
    var words = [];
    for (var i = 0; i < utf16StrLength; i++) {
      words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16);
    }
    return WordArray.create(words, utf16StrLength * 2);
  }
}